<?php

namespace app\admin\model;

use think\exception\ValidateException;
use support\facade\Filesystem;
use think\Image;
use think\Model;

class UploadFiles extends Model
{
    protected $name = 'upload_files';


public function upload($class_id=1, $folder_name='files', $app=2, $user_id=0, $file='file', $exts=[])
{
    if (empty($exts)) {
        $exts = ['png','jpg','jpeg','gif','bmp','doc','docx','csv','xls','xlsx','xlsm','pdf'];
    }

    try {
        $param = request()->all();
        $file = request()->file($file);
        if (!$file) {
            return ['code'=>0, 'msg'=>'未检测到上传文件'];
        }
        $ext = strtolower(pathinfo($file->getUploadName(), PATHINFO_EXTENSION));
        if (!in_array($ext, $exts)) {
            return ['code'=>0, 'msg'=>'格式不允许'];
        }

        // 先获取文件信息
        $originName = $file->getUploadName();
        $fileSize = $file->getSize();

        // 保存路径
        $saveDir = public_path() . "/storage/{$folder_name}/" . date('Ymd');
        if (!is_dir($saveDir)) {
            mkdir($saveDir, 0777, true);
        }
        $saveName = uniqid() . '.' . $ext;
        $file->move($saveDir . '/' . $saveName);

        $file_path = '/storage/' . $folder_name . '/' . date('Ymd') . '/' . $saveName;
        $insert_data = [
            'url'        => $file_path,
            'class_id'   => $class_id,
            'app'        => $app,
            'user_id'    => intval($user_id),
            'file_name'  => $originName,
            'file_size'  => $fileSize,
            'file_type'  => 'image',
            'extension'  => $ext,
            'created_at' => time()
        ];
        $insert = self::create($insert_data);
        $success = [
            'id'        => $insert['id'],
            'url'       => $file_path,
            'file'      => $file_path,
            'file_name' => $originName,
            'file_size' => $fileSize,
            'ext'       => $ext
        ];
        return ['code'=>200, 'msg'=>'success', 'data'=>$success];
    } catch (ValidateException $e) {
        return ['code'=>500, 'msg'=>$e->getMessage()];
    }
}

    public function delStorageFile($storage, $file_path)
    {
        if( $storage == 'local' ) {
            $file_path = public_path().ltrim($file_path,'/');
            if( file_exists($file_path) ) {
                unlink($file_path);
            }
        }
    }


}